package com.alex.megacj.affiliate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import org.springframework.beans.factory.InitializingBean;

public class AffiliateLinkRewriter implements InitializingBean {

	private List<RewriteRule> rewriteRules = Collections.emptyList();
	
	private Map<String, RewriteRule> map;

	public void setRewriteRules(List<RewriteRule> rewriteRules) {
		this.rewriteRules = rewriteRules;
	}

	public String rewriteURL(String host, String url) throws AffiliateLinkRewriteException {
		RewriteRule rule = map.get(host);
		if (rule == null) {
			throw new AffiliateLinkRewriteException();
		}
		if (rule.getAffiliateId() == null) {
			return tds(url);
		}
		Matcher matcher = rule.getPattern().matcher(url);
		if (!matcher.find()) {
			throw new AffiliateLinkRewriteException();
		}
		return tds(url.substring(0, matcher.start(1)) + rule.getAffiliateId() + url.substring(matcher.end(1)));
	}

	private String tds(String url) {
		try {
			return "http://mahentohen.com/in.cgi?3&go=" + URLEncoder.encode(url.substring("http://".length()), "utf-8");
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		map = new HashMap<String, RewriteRule>();
		for (RewriteRule rule : rewriteRules) {
			map.put(rule.getHost(), rule);
		}
	}
}
